import Koa from 'koa';
import Router from 'koa-router';
import cors from 'koa-cors';
import UserController from './controllers/UserController/User.controller';
import { connectionDataBase } from './config/database';
import redis from './config/redisConfig';
import adminGuard from './guard/AdminGuard';
import commonErrorFilter from './Filter/commonErrorFilter';
import winstonLogger from './Logger/logger';
import AdminController from './controllers/AdminController/Admin.controller';
import TestController from './controllers/TestController/Test.controller';
import koaBody from 'koa-body';
import serve from 'koa-static';
import mount from 'koa-mount';
import path from 'node:path';
import * as fs from 'fs';
import koaLogger from 'koa-logger';
import userGuard from './guard/UserGuard';
import ProductController from './controllers/ProductController/Product.controller';
import ProductCategoryController from './controllers/ProductCategory/ProductCategory.controller';


const app = new Koa();
const router = new Router();
const isProduction = process.env.NODE_ENV === 'production';

app.use(commonErrorFilter);
app.use(koaLogger());
app.use(cors());
app.use(router.allowedMethods());
app.use(adminGuard);
app.use(userGuard);
//托管静态文件
//生产环境跟开发环境路径不一样
app.use(mount('/assets', isProduction ? serve(path.join(__dirname, '/assets')) : serve('./assets')));

app.use(koaBody());
app.use(router.routes());
app.use(AdminController);
app.use(ProductController);
app.use(ProductCategoryController);
app.use(UserController);
app.use(TestController);


//排到最后
router.get('/html', async (ctx) => {
  fs.readFile(path.join(__dirname, '../public/index.html'), (err, data) => {
    if (err) {
      ctx.body = '404';
    } else {
      ctx.body = data;
    }
  });
});
connectionDataBase().then(() => {
  winstonLogger.info('数据库连接成功');
  redis.on('connect', () => {
    winstonLogger.info('Redis连接成功');
  });
  redis.on('error', (err) => {
    winstonLogger.error('Redis连接失败');
  });
  app.listen(3000, () => {
    winstonLogger.info('Server is running on port 3000');
  });
  app.on('error', (err) => {
    winstonLogger.error('Server error', err);
  });
});